package lingou.homework.postbar.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lingou.homework.postbar.controller.proto.resp.Response;
import lingou.homework.postbar.controller.tool.LogPrinter;
import lingou.homework.postbar.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.*;

@RestControllerAdvice
public class ExceptionHandler {
    @Autowired
    LogPrinter logPrinter;
    private ObjectMapper objectMapper = new ObjectMapper();
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public Response doException(Exception e){
        if(e instanceof BusinessException businessException){
            Response response = Response.ofFailure(1, businessException.getMessage());
            logPrinter.printlnDepth(1, "Resp:", objectMapper.valueToTree(response));
            return response;
        }
        Response response = Response.ofUnknownError(e.getMessage());
        StringWriter out = new StringWriter();
        e.printStackTrace(new PrintWriter(out));
        logPrinter.printlnDepth(1, out.toString());
        logPrinter.printlnDepth(1, "Resp:", response);
        return response;
    }
}
